package cn.bugstack.infrastructure.event;

import cn.bugstack.types.event.BaseEvent;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: Zchy
 * @Description: 消息发送
 * @DateTime: 12/1/2024 4:42 PM
 **/
@Slf4j
@Component
public class EventPublisher {

    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    public void publish(String topic, BaseEvent.EventMessage<?> eventMessage) {
        try {
            String messageString = JSON.toJSONString(eventMessage);
            kafkaTemplate.send(topic, messageString);
            log.info("发送MQ消息 topic: {} message: {}", topic, messageString);
        } catch (Exception e) {
            log.error("发送MQ消息失败 topic: {} message: {}", topic, JSON.toJSONString(eventMessage), e);
            throw e;
        }
    }

    public void publish(String topic, String eventMessage) {
        try {
            kafkaTemplate.send(topic, eventMessage);
            log.info("发送MQ消息 topic: {} message: {}", topic, eventMessage);
        } catch (Exception e) {
            log.error("发送MQ消息失败 topic: {} message: {}", topic, JSON.toJSONString(eventMessage), e);
            throw e;
        }
    }
}
